<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\Banner;
use app\common\model\GoodsAttr;
use app\common\model\GoodsCart;
use app\common\model\Address;
use app\common\model\Order;
use app\common\model\Goods;
use app\common\model\User;
use think\Db;

/**
 * 购物车接口
 */
class Cart extends Api
{
    public function _initialize()
    {
        parent::_initialize();
    }
    /**
     * 购物车列表
     * @param string $token      用户token
     * @ApiReturn   ({
    "code": 1,
    "msg": "",
    "time": "1618801888",
    "data": [
    {
    "id": 5,购物车ID
    "num": 4,数量
    "goods_id": 3,商品ID
    "images": "http://www.shop.com/uploads/20210406/998bcbc925dd59eb924d7a100b9c0d1f.png",图片
    "name": "香辣酱2",名称
    "price": "40.00",单价
    "attr_name": "330ml"规格名称
    },
    {
    "id": 4,
    "num": 3,
    "images": "http://www.shop.com/uploads/20210406/998bcbc925dd59eb924d7a100b9c0d1f.png",
    "name": "香辣酱1",
    "price": "80.00",
    "attr_name": "1000ml"
    },
    {
    "id": 3,
    "num": 2,
    "images": "http://www.shop.com/uploads/20210406/998bcbc925dd59eb924d7a100b9c0d1f.png",
    "name": "香辣酱",
    "price": "25.00",
    "attr_name": "50g"
    }
    ]
    })
     */
    public function cart_list()
    {
        $token = $this->request->get('token');
        $user_info = User::where('token',$token)->field('id')->find();
        $list = GoodsCart::alias('c')->join('goods g','g.id = c.goods_id')->join('goods_attr a','a.goods_id = g.id')->where('c.userid',$user_info['id'])->where('g.status',0)->order('c.id desc')->field('c.id,c.num,g.id as goods_id,g.images,g.name,a.price,a.attr_name')->select();
        foreach($list as &$value1){
            $images = explode(',',$value1['images']);
            $value1['images'] = $this->domain.$images[0];
        }
        $this->success($list);
    }
    /**
     * 购物车推荐商品列表
     * @param string $token      用户token
     * @param int $page 页数，默认1
     * @ApiReturn   ({
    "code": 1,
    "msg": "",
    "time": "1618801888",
    "data": [
    {
    "id": 1,商品ID
    "images": "http://www.shop.com/uploads/20210406/998bcbc925dd59eb924d7a100b9c0d1f.png",图片
    "name": "香辣酱",名称
    "price": "25.00",价格
    "attr_name": "50g",规格
    "status_text": ""
    },
    {
    "id": 3,
    "images": "http://www.shop.com/uploads/20210406/998bcbc925dd59eb924d7a100b9c0d1f.png",
    "name": "香辣酱2",
    "price": "40.00",
    "attr_name": "330ml",
    "status_text": ""
    },
    {
    "id": 2,
    "images": "http://www.shop.com/uploads/20210406/998bcbc925dd59eb924d7a100b9c0d1f.png",
    "name": "香辣酱1",
    "price": "25.00",
    "attr_name": "1000ml",
    "status_text": ""
    },
    {
    "id": 4,
    "images": "http://www.shop.com/uploads/20210406/998bcbc925dd59eb924d7a100b9c0d1f.png",
    "name": "香辣酱3",
    "price": "80.00",
    "attr_name": "500ml",
    "status_text": ""
    }
    ]
    })
     */
    public function recommend_list()
    {
        $pagesize = 10;
        $page  = $this->request->get('page')==null?1:$this->request->get('page');
        $page = ($page-1)*$pagesize;
        //推荐商品
        $goods_list = Goods::where('status',0)->where('is_recommend',1)->field('id,images,name,price,is_recommend')->limit($page,$pagesize)->order('recommendtime desc')->select();
        foreach($goods_list as &$value){
            $images = explode(',',$value['images']);
            $value['images'] = $this->domain.$images[0];
            $attr_info = GoodsAttr::where('goods_id',$value['id'])->order('id asc')->field('id,attr_name')->find();
            $value['attr_name'] = $attr_info['attr_name'];
            $value['attr_id'] = $attr_info['id'];
        }
        $this->success($goods_list);
    }


    /**
     * 添加购物车
     * @ApiMethod   (POST)
     * @param string $token      用户token
     * @param string $goods_id      商品ID
     * @param string $attr_id      商品规格ID
     * @param string $num      商品数量
     * @ApiReturn   ({
    "code": 200,
    "msg": "请求成功",
    "time": "1596684503",
    "data": [
    0.06,
    0.01
    ]
    })
     */
    public function join_cart()
    {
        $token = $this->request->post('token');
        $goods_id = $this->request->post('goods_id');
        $attr_id = $this->request->post('attr_id');
        $num = $this->request->post('num');
        $user_info = User::where('token',$token)->field('id')->find();
        $goods_info = GoodsAttr::where(['goods_id'=>$goods_id,'id'=>$attr_id])->find();
        if($goods_info){
            if(intval($num)<=0){
                $this->error('添加数量错误');
            }
            if($num > $goods_info['stock']){
                $this->error('添加数量大于库存');
            }
            $cart_count = GoodsCart::where(['goods_id'=>$goods_id,'attr_id'=>$attr_id,'userid'=>$user_info['id']])->count();
            if($cart_count){
                $this->error('该商品已经在您的购物车了');
            }
            $data = [
                'userid'=>$user_info['id'],
                'goods_id'=>$goods_id,
                'attr_id'=>$attr_id,
                'num'=>$num,
            ];
            Db::startTrans();
            try {
                $res = GoodsCart::create($data);
                Db::commit();
            } catch (Exception $e) {
                $this->error($e->getMessage());
                Db::rollback();
                return false;
            }
            if($res){
                $this->success('','添加成功');
            }else{
                $this->error('添加失败');
            }
        }else{
            $this->error('数据异常');
        }
    }
    /**
     * 购物车加减
     * @ApiMethod   (POST)
     * @param string $token      用户token
     * @param string $cart_id      商品规格ID
     * @param string $num      数量
     * @ApiReturn   ({
    "code": 200,
    "msg": "请求成功",
    "time": "1596684503",
    "data": [
    0.06,
    0.01
    ]
    })
     */
    public function action_cart()
    {
        $token = $this->request->post('token');
        $cart_id = $this->request->post('cart_id');
        $num = $this->request->post('num');
        $user_info = User::where('token',$token)->field('id')->find();
        $cart_info = GoodsCart::where(['id'=>$cart_id,'userid'=>$user_info['id']])->find();
        if($cart_info){
            $goods_info = GoodsAttr::where(['goods_id'=>$cart_info['goods_id'],'id'=>$cart_info['attr_id']])->find();
            if($goods_info){
                if(intval($num)<=0){
                    $this->error('数量错误');
                }
                if($num > $goods_info['stock']){
                    $this->error('数量大于库存');
                }
                Db::startTrans();
                try {
                    $res = GoodsCart::where('id',$cart_id)->update(['num'=>$num]);
                    Db::commit();
                } catch (Exception $e) {
                    $this->error($e->getMessage());
                    Db::rollback();
                    return false;
                }
                if($res){
                    $this->success('','操作成功');
                }else{
                    $this->error('操作失败');
                }
            }
        }else{
            $this->error('数据异常');
        }
    }
    /**
     * 删除购物车商品
     * @ApiMethod   (POST)
     * @param string $token      用户token
     * @param string $cart_id      购物车ID,逗号隔开
     * @ApiReturn   ({
    "code": 200,
    "msg": "请求成功",
    "time": "1596684503",
    "data": [
    0.06,
    0.01
    ]
    })
     */
    public function del_cart()
    {
        $token = $this->request->post('token');
        $cart_id = $this->request->post('cart_id');
        $user_info = User::where('token',$token)->field('id')->find();
        Db::startTrans();
        try {
            $res =GoodsCart::where(['userid'=>$user_info['id']])->where('id','in',$cart_id)->delete();
            Db::commit();
        } catch (Exception $e) {
            $this->error($e->getMessage());
            Db::rollback();
            return false;
        }
        if($res){
            $this->success('','删除成功');
        }else{
            $this->error('删除失败');
        }
    }
    /**
     * 购物车结算页面
     * @param string $token 用户token
     * @param string $cart_id 购物车ID,逗号隔开
     * @ApiReturn   ({
    "code": 1,
    "msg": "",
    "time": "1618802564",
    "data": {
    "goods_list": [
    {
    "id": 5,购物车ID
    "num": 4,数量
    "images": "http://www.shop.com/uploads/20210406/998bcbc925dd59eb924d7a100b9c0d1f.png",图片
    "name": "香辣酱2",名称
    "price": "40.00",单价
    "attr_name": "330ml",规格名称
    "stock": 1000,库存
    },
    {
    "id": 4,
    "num": 3,
    "images": "http://www.shop.com/uploads/20210406/998bcbc925dd59eb924d7a100b9c0d1f.png",
    "name": "香辣酱1",
    "price": "80.00",
    "attr_name": "1000ml",
    "stock": 1000,
    "tprice": 240
    },
    {
    "id": 3,
    "num": 2,
    "images": "http://www.shop.com/uploads/20210406/998bcbc925dd59eb924d7a100b9c0d1f.png",
    "name": "香辣酱",
    "price": "25.00",
    "attr_name": "50g",
    "stock": 1000,
    }
    ],
    "total_price": 450,总价
    "address": {收货地址
    "id": 1,
    "userid": 1,
    "province": "北京",
    "city": "北京市",
    "area": "东城区",
    "address": "北京北京市东城区三路屯商户",收货地址，已经拼接好
    "username": "张三",姓名
    "mobile": "13454152145",电话
    "is_default": 1,
    "createtime": null
    }
    }
    })
     */
    public function confirm_order()
    {
        $token = $this->request->get('token');
        $user_info = User::where('token', $token)->field('id')->find();
        $cart_id = $this->request->get('cart_id');
        $goods_list = GoodsCart::alias('c')->join('goods g','g.id = c.goods_id')->join('goods_attr a','a.id = c.attr_id')->where('c.userid',$user_info['id'])->where('c.id','in',$cart_id)->field('c.id,c.num,g.images,g.name,a.price,a.attr_name,a.stock')->order('c.id desc')->select();
        $total_price = 0;
        foreach($goods_list as &$value){
            $images = explode(',', $value['images']);
            $value['images'] = $this->domain.$images[0];
            if ($value['num'] > $value['stock']) {
                $this->error($value['name'].'购买数量大于库存');
            }
            $total_price += $value['price'] * $value['num'];
        }
        //收货地址
        $address = Address::where(['userid' => $user_info['id'], 'is_default' => 1])->find();
        if($address){
            $address['address'] = $address['province'].$address['city'].$address['area'].$address['address'];
        }
        $data = [
            'goods_list' => $goods_list,
            'total_price' => $total_price,
            'address' => $address,
        ];
        $this->success($data);
    }
    /**
     * 购物车支付
     * @ApiMethod   (POST)
     * @param string $token 用户token
     * @param string $cart_id 购物车ID,逗号隔开
     * @param string $address_id 收货地址ID
     * @param string $type 支付方式1支付宝2微信
     * @param string $note 备注
     * @ApiReturn   ({
    "code": 200,
    "msg": "请求成功",
    "time": "1596684503",
    "data": [
    0.06,
    0.01
    ]
    })
     */
    public function buy_now()
    {
        $token = $this->request->post('token');
        $user_info = User::where('token', $token)->field('id')->find();
        $address_id = $this->request->post('address_id');
        $note = $this->request->post('note');
        $type = $this->request->post('type');
        $cart_id = $this->request->post('cart_id');
        //收货地址
        if($address_id){
            $address_info  = Address::where(['userid'=>$user_info['id'],'id'=>$address_id])->find();
            if(empty($address_info)){
                $this->error('收货地址不存在');
            }
        }
        $total_price = 0;
        $goods_list = GoodsCart::alias('c')->join('goods g','g.id = c.goods_id')->join('goods_attr a','a.id = c.attr_id')->where('c.userid',$user_info['id'])->where('c.id','in',$cart_id)->field('c.id,c.num,g.images,g.name,g.id as goods_id,a.id as attr_id,a.price,a.attr_name,a.stock')->order('c.id desc')->select();
        if(empty($goods_list)){
            $this->error('购物车没有商品');
        }
        foreach($goods_list as &$value1) {
            if (intval($value1['num']) > $value1['stock']) {
                $this->error($value1['name'] . '购买数量大于库存');
            }
            $images = explode(',', $value1['images']);
            //总价
            $total_price += $value1['price'] * $value1['num'];
            $arr1 = [
                'goods_id'=>$value1['goods_id'],
                'attr_id'=>$value1['attr_id'],
                'goods_name'=>$value1['name'],
                'goods_image'=> $images[0],
                'attr_name'=>$value1['attr_name'],
                'unit_price'=>$value1['price'],
                'num'=>$value1['num'],
                'createtime'=>time(),
            ];
            $order_goods[] = $arr1;
        }
        //实际支付金额
        $actual_price = $total_price ;
        $order = [
            'order_sn'=> getOrderSn(),
            'userid'  =>$user_info['id'],
            'price'  =>$total_price,
            'discounted_price'=>0,
            'actual_price'=>$actual_price,
            'username'=>$address_info['username'],
            'mobile'=>$address_info['mobile'],
            'address'=>$address_info['province'].$address_info['city'].$address_info['area'].$address_info['address'],
            'is_coupon'=>0,
            'note'=>$note,
            'paytype'=>$type,
            'createtime'=>time(),
        ];
        //print_r($value2);
        Db::startTrans();
        try {
            $res = Order::insertGetId($order);
            if($res){
                foreach($order_goods as &$value3){
                    //购物车删除购买商品
                    GoodsCart::where(['goods_id'=>$value3['goods_id'],'attr_id'=>$value3['attr_id'],'userid'=>$user_info['id']])->delete();
                    //print_r($value3);exit;
                        //unset($value3['bus_id']);
                    $value3['order_id'] = $res;
                    $res1 = Db::name('order_goods')->insert($value3);
                }
            }
            Db::commit();
        } catch (ValidateException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (PDOException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if($res && $res1){
            if($type == 1){
                //支付宝支付
                $title = '订单信息'.$order['order_sn'];
                $amount = abs($total_price);
                $notify_url =  $this->request->root(true) . '/api/pays/goods_response/type/alipay';
                //$result = ali_pay($title,$notify_url,$amount,$order['order_sn']);
                $result = \addons\epay\library\Service::submitOrder($amount,$order['order_sn'],'alipay',$title,$notify_url,'','app');
                $this->success($result);
            }elseif($type ==2){
                //微信支付
                $title = '订单信息'.$order['order_sn'];
                $amount = abs($total_price);
                $notify_url =  $this->request->root(true) . '/api/pays/goods_response/type/wechat';
                //$result = wechat_pay($title,$notify_url,$amount,$order['order_sn']);
                $result = \addons\epay\library\Service::submitOrder($amount,$order['order_sn'],'wechat',$title,$notify_url,'','app');
                $this->success($result);
            }
        }
        $this->error('数据异常');
    }
}
